package com.qiaofang.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.qiaofang.common.utils.SpringUtil;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.service.BatchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class BatchReportListener extends AnalysisEventListener<BatchReport> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BatchReportListener.class);

    private BatchService batchService = SpringUtil.getBean(BatchService.class);

    // 时分秒都齐全的时间格式
    private String timeWithHmsReg = "([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";

    /**
     * 每隔5条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    List<BatchReport> list = Lists.newArrayList();

    @Override
    public void invoke(BatchReport data, AnalysisContext context) {
        Pattern pattern = Pattern.compile(timeWithHmsReg);
        log.info("partner phone: {}, customer phone: {}", data.getPartnerPhone(), data.getCustomerPhone());
        if(StringUtils.isNotBlank(data.getPartnerPhone()) && StringUtils.isNotBlank(data.getCustomerPhone())){
            String createdTime = data.getCreatedTime();
            if(StringUtil.isNotBlank(createdTime)){
                if(!pattern.matcher(createdTime).find()){
                    createdTime += ":00";
                }
                createdTime = createdTime.replaceAll("/", "-");
                data.setCreatedTime(createdTime);
            }
            String reportProtectTime = data.getReportProtectTime();
            if(StringUtil.isNotBlank(reportProtectTime)){
                if(!pattern.matcher(reportProtectTime).find()){
                    reportProtectTime += ":00";
                }
                reportProtectTime = reportProtectTime.replaceAll("/", "-");
                data.setReportProtectTime(reportProtectTime);
            }
            String validTime = data.getValidTime();
            if(StringUtil.isNotBlank(validTime)){
                if(!pattern.matcher(validTime).find()){
                    validTime += ":00";
                }
                validTime = validTime.replaceAll("/", "-");
                data.setValidTime(validTime);
            }
            String visitProtectTime = data.getVisitProtectTime();
            if(StringUtil.isNotBlank(visitProtectTime)){
                if(!pattern.matcher(visitProtectTime).find()){
                    visitProtectTime += ":00";
                }
                visitProtectTime = visitProtectTime.replaceAll("/", "-");
                data.setVisitProtectTime(visitProtectTime);
            }
            String visitTime = data.getVisitTime();
            if(StringUtil.isNotBlank(visitTime)){
                if(!pattern.matcher(visitTime).find()){
                    visitTime += ":00";
                }
                visitTime = visitTime.replaceAll("/", "-");
                data.setVisitTime(visitTime);
            }
            String dealDate = data.getDealDate();
            if(StringUtil.isNotBlank(dealDate)){
                if(!pattern.matcher(dealDate).find()){
                    dealDate += ":00";
                }
                dealDate = dealDate.replaceAll("/", "-");
                data.setDealDate(dealDate);
            }

            // 复制的手机号存在万恶的万国码,手机号做个特殊处理
            String partnerPhone = data.getPartnerPhone();
            String actualPartnerPhone = "";
            for (int ii=0; ii < partnerPhone.length(); ii++){
                if(partnerPhone.charAt(ii)>=48 && partnerPhone.charAt(ii)<=57){
                    actualPartnerPhone += partnerPhone.charAt(ii);
                }
            }

            String customerPhone = data.getCustomerPhone();
            String actualCustomerPhone = "";
            for (int ii=0; ii < customerPhone.length(); ii++){
                if(customerPhone.charAt(ii)>=48 && customerPhone.charAt(ii)<=57){
                    actualCustomerPhone += customerPhone.charAt(ii);
                }
            }

            data.setPartnerPhone(actualPartnerPhone);
            data.setCustomerPhone(actualCustomerPhone);
            list.add(data);
        }
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        List<List<BatchReport>> partitions = com.google.common.collect.Lists.partition(list, 500);
        for (List<BatchReport> list : partitions){
            batchService.batchSaveReport(list);
        }
    }

}
